package com.ss.springboot1.device.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ss.springboot1.common.exception.DeviceBusinessException;
import com.ss.springboot1.device.dto.DeviceReqData;
import com.ss.springboot1.device.service.DeviceService;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/device")
public class DeviceController {
    @Resource
    private DeviceService deviceService;

    //查询状态
    @GetMapping("/getStatus")
    public ResponseEntity<?> getStatus(@RequestParam int channel) {
        log.info("查询通道{}状态", channel);
        Map<String, Object> statusMap = deviceService.getChannelStatus(channel);
        return ResponseEntity.ok(statusMap);
    }

    //设置电流
    @PostMapping("/setCurrent")
    public ResponseEntity<String> setCurrent(@RequestBody DeviceReqData deviceReqData) throws JsonProcessingException {
        log.info("接收到设置电流请求");
        String result = deviceService.setCurrent(deviceReqData);
        if (result.startsWith("ERROR:")) {
            String errorMsg = result.substring(6);
            throw new DeviceBusinessException(errorMsg);
        }
        return ResponseEntity.ok(result);
    }

    //设置输出
    @PostMapping("/setPut")
    public ResponseEntity<String> setPut(@RequestBody DeviceReqData deviceReqData) throws JsonProcessingException {
        log.info("接收到设置输出请求");
        String result = deviceService.setPut(deviceReqData);

        if (result.startsWith("ERROR:")) {
            String errorMsg = result.substring(6);
            throw new DeviceBusinessException(errorMsg);
        }
        return ResponseEntity.ok(result);
    }

    //设置使能
    @PostMapping("/setEnable")
    public ResponseEntity<String> setEnable(@RequestBody DeviceReqData deviceReqData) throws JsonProcessingException {
        log.info("接收到设置使能请求");
        String result = deviceService.setEnable(deviceReqData);
        if (result.startsWith("ERROR:")) {
            String errorMsg = result.substring(6);
            throw new DeviceBusinessException(errorMsg);
        }
        return ResponseEntity.ok(result);
    }

    //获取12个通道的状态
    @GetMapping("/getAllStatus")
    public ResponseEntity<?> getAllStatus() {
        return ResponseEntity.ok(deviceService.getAllChannelStatus());
    }
}
